package com.xiaodeng.edu.controller;

import cn.hutool.core.bean.BeanUtil;
import com.xiaodeng.edu.pojo.Admin;
import com.xiaodeng.edu.pojo.PageBean;
import com.xiaodeng.edu.pojo.Result;
import com.xiaodeng.edu.pojo.User;
import com.xiaodeng.edu.pojo.dto.AdminDto;
import com.xiaodeng.edu.service.AdminService;
import com.xiaodeng.edu.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Validated
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    //管理员注册
    @PostMapping("/register")
    public Result register(@Length(min = 6,max = 18,message = "管理员名长度必须是6-18位") String adminUser,
                           @Length(min = 6,max = 18,message = "密码长度必须是6-18位") String password)
    {
        adminService.register(adminUser,password);
        return Result.success("注册成功");
    }

    //管理员登录
    @PostMapping ("/login")
    public Result<String> login(@Validated String adminUser,String password) {
        String token = adminService.login(adminUser, password);
        return Result.success("登陆成功",token);
    }

    //删除管理员
    @DeleteMapping("/delete")
    public Result delete(Integer id){
        adminService.delete(id);
        return Result.success("删除成功");
    }

    //更新管理员头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        adminService.updateAvatar(avatarUrl);
        return Result.success();
    }

    //管理员修改信息
    @PatchMapping("/update")
    public Result<Admin> update(@Validated @RequestBody Admin admin){
        adminService.update(admin);
        return Result.success("修改成功");
    }


    //管理员修改密码
    @PatchMapping("/updatePwd")
    public Result<Admin> updatePwd(@RequestBody @Validated AdminDto adminDto){
        Admin admin = BeanUtil.copyProperties(adminDto,Admin.class);
        String newPwd = adminDto.getNewPwd();
        adminService.updatePwd(newPwd,admin);
        return Result.success("修改成功");
    }
    //查询管理员信息
    @GetMapping("/userInfo")
    public Result<Admin> userInfo(){
        //根据用户名查询用户
        Map<String,Object> map = ThreadLocalUtil.get();
        String admin_name =(String) map.get("admin_name");
        System.out.println(admin_name);
        Admin admin = adminService.findByUserName(admin_name);
        return Result.success(admin);
    }
    //查询用户列表
    @GetMapping("/userlist")
    public Result<PageBean<User>> userlist(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) String username
    ){
        PageBean<User> pb = adminService.userlist(pageNum,pageSize,username);
        return Result.success(pb);
    }
}
